import { BASE_URL } from "../config";
import { queryString } from "./url";
import { Toast } from "antd-mobile";
import { UploadOutline } from "antd-mobile-icons";

export class API {
  /**
   *
   * @param {*} partialUrl
   * @param {String} method
   * @param {*} contentType
   * @param {*} query
   * @param {*} body
   */
  async request(
    partialUrl,
    query,
    data,
    method = "GET",
    contentType = "application/json",
    body
  ) {
    // const isQuery = method.includes(['GET', 'HEAD']);
    const isQuery = ["GET", "HEAD"].includes(method);

    return (
      await fetch(BASE_URL + partialUrl + (query ? queryString(query) : ""), {
        method,
        headers: {
          ...(isQuery ? null : { "Content-Type": contentType }),
        },
        ...(isQuery ? null : { body: JSON.stringify(data) }),
      })
    ).json();
  }

  get(partialUrl, query) {
    return this.request(partialUrl, query);
  }

  post(partialUrl, data, query) {
    return this.request(partialUrl, query, data, "POST");
  }
}

let count = 0;
/**
 * 传递一个 Promise 对象，并自动的开启 Loading 效果 和 关闭。
 * @param {Promise} promise 异步 Promise 对象
 */
export const loading = async (promise) => {
  // 开启 Loading 效果。
  Toast.show({
    content: "加载中",
    icon: "loading",
    duration: 0,
  });

  count++;

  // 执行传递的 Promise，返回 promise 结果。
  try {
    // 阻塞 try..
    await promise;
    // Promise 成功后返回 Promise
    return promise;
  } finally {
    // 关闭 Toast
    --count || Toast.clear();
  }
};
